package a66weding.com.jiehuntong.activity.toolsholiday;

import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import java.io.File;
import java.util.Calendar;
import java.util.List;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.DayBean;
import a66weding.com.jiehuntong.common.utils.CalendarUtil;
import a66weding.com.jiehuntong.common.utils.DateUtils;
import a66weding.com.jiehuntong.common.utils.LunarCalendar;
import a66weding.com.jiehuntong.dao.HolidayDbDao;
import a66weding.com.jiehuntong.view.holiday.MonthDateView;
import a66weding.com.jiehuntong.widgets.wheelview.OnWheelChangedListener;
import a66weding.com.jiehuntong.widgets.wheelview.WheelView;
import a66weding.com.jiehuntong.widgets.wheelview.adapters.ArrayWheelAdapter;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;

public class ToolsHolidayActivity extends SwipeBackActivity implements View.OnClickListener, OnWheelChangedListener {
    private TextView mTitleTv;
    private TextView mBackTv;
    private TextView mHeadRightfuncTv;
    private LinearLayout mBackLay;
    private LinearLayout mSelectPlaceLay;

    private ImageView mLeftIv;
    private ImageView mRightIv;
    private TextView mTitleMonthTv;
    private TextView mDateTv;
    private TextView mIsHolidayTv;
    private TextView mLunarTv;
    private TextView mWeekTv;
    private TextView mAfterTv;
    private TextView mCandoTv;
    private TextView mCanNotdoTv;
    private MonthDateView monthDateView;

    private SQLiteDatabase database;
    public static final int DBSUCESS = 1;
    public static final int DBFAIL = 2;
    public static final String DB_NAME = "hdjr.db";
    private File file;
    private HolidayDbDao holidayDbDao;



    public static final int CANWEDDING=1;
    private static final int NOMAL=2;
    private static final int CANNOTWEDDING=3;

    private SpannableStringBuilder ssb;
    private int lastYear;
    private int lastMonth;
    private int lastDay;
    private int mCurrYear,mCurrMonth,mCurrDay;

    private WheelView mViewYear;
    private WheelView mViewMonth;
    private PopupWindow mDatePopupWindow;

    private int mSelectYear;
    private int mSelectMonth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tools_holiday);
        ((GlobalApplication)getApplication()).getActivityManager().addActivity("ToolsHolidayActivity",this);

        holidayDbDao = new HolidayDbDao(this);
        initview();

        initdata();
    }



    private void initview() {
        mTitleTv = (TextView) findViewById(R.id.tv_header_title);
        mBackTv = (TextView) findViewById(R.id.tv_header_backcontent);
        mBackLay = (LinearLayout) findViewById(R.id.llay_header_back);
        mSelectPlaceLay = (LinearLayout) findViewById(R.id.lay_header_place);
        mHeadRightfuncTv = (TextView) findViewById(R.id.tv_header_function);

        mTitleTv.setText("结婚吉日");
        mHeadRightfuncTv.setText("查年份");

        mLeftIv = (ImageView) findViewById(R.id.leftButton);
        mRightIv = (ImageView) findViewById(R.id.rightButton);
        monthDateView = (MonthDateView) findViewById(R.id.monthDateView);
        mTitleMonthTv = (TextView) findViewById(R.id.dateTitle);
        mDateTv = (TextView) findViewById(R.id.tv_dateTv);
        mIsHolidayTv = (TextView) findViewById(R.id.tv_isholiday);
        mLunarTv = (TextView) findViewById(R.id.tv_lunar);
        mWeekTv  =(TextView) findViewById(R.id.tv_week);
        mAfterTv = (TextView) findViewById(R.id.tv_after);
        mCandoTv = (TextView) findViewById(R.id.textView_cando);
        mCanNotdoTv = (TextView) findViewById(R.id.textView_canotdo);

        mAfterTv.setVisibility(View.GONE);

        monthDateView.setDateClick(new MonthDateView.DateClickListener() {
            @Override
            public void onDateClick() {//判断是否重复点击
                int selectYear = monthDateView.getmSelYear();
                int selectMonth = monthDateView.getmSelMonth()+1;
                int day = monthDateView.getmSelDay();
                String selectWeek = monthDateView.getSelectWeek();
                if(lastYear==selectYear && lastMonth==selectMonth && lastDay==day) {
                    return;
                }

                notifyData(selectYear,selectMonth,day,selectWeek);
            }
        });

        monthDateView.setPageChangeListener(new MonthDateView.PageChangeListener() {
            @Override
            public void onPageChange(int year, int month) {
                List monthHoliday = holidayDbDao.getMonthHoliday(year, month);
                monthDateView.setHolidayList(monthHoliday);


                mTitleMonthTv.setText(year+"年"+month+"月");
            }
        });

        mLeftIv.setOnClickListener(this);
        mRightIv.setOnClickListener(this);
        mBackLay.setOnClickListener(this);
        mHeadRightfuncTv.setOnClickListener(this);

    }

    private void initdata() {
        Calendar calendar = Calendar.getInstance();
        mCurrYear = calendar.get(Calendar.YEAR);
        mCurrMonth = calendar.get(Calendar.MONTH)+1;
        mCurrDay = calendar.get(Calendar.DATE);
        int week = calendar.get(Calendar.DAY_OF_WEEK);
        String weekName2 = DateUtils.getWeekName2(week);

        List monthHoliday = holidayDbDao.getMonthHoliday(mCurrYear, mCurrMonth);
        monthDateView.setHolidayList(monthHoliday);

        mTitleMonthTv.setText(mCurrYear+"年"+mCurrMonth+"月");

        monthDateView.setSelectYearMonth(mCurrYear,mCurrMonth-1,mCurrDay);
        notifyData(mCurrYear,mCurrMonth,mCurrDay,weekName2);


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.leftButton:
                monthDateView.onLeftClick();
                int year1 = monthDateView.getmSelYear();
                int month1 = monthDateView.getmSelMonth()+1;
                mTitleMonthTv.setText(year1+"年"+month1+"月");
                break;
            case R.id.rightButton:
                monthDateView.onRightClick();
                int year2 = monthDateView.getmSelYear();
                int month2 = monthDateView.getmSelMonth()+1;
                mTitleMonthTv.setText(year2+"年"+month2+"月");
                break;
            case R.id.tv_header_function:
                showdatePopupWindow(view);
                break;
            case R.id.tv_confim:
                List monthHoliday = holidayDbDao.getMonthHoliday(mSelectYear, mSelectMonth);
                monthDateView.setHolidayList(monthHoliday);

                mTitleMonthTv.setText(mSelectYear+"年"+mSelectMonth+"月");
                monthDateView.setSelectDate(mSelectYear,mSelectMonth-1,mCurrDay);

                if(mDatePopupWindow!=null) {
                    mDatePopupWindow.dismiss();
                }
                break;
            case R.id.tv_cancel:
                if(mDatePopupWindow!=null) {
                    mDatePopupWindow.dismiss();
                }
                break;
            case R.id.llay_header_back:
                finish();
                break;

        }
    }

    private void notifyData(int selectYear,int selectMonth,int day,String selectWeek){
        int[] lunDayInfo = LunarCalendar.solarToLunar(selectYear, selectMonth, day);
        String chinaMonthString = DateUtils.getLunMonth(lunDayInfo[1]);
        String chinaDayString = CalendarUtil.getChinaDayString(lunDayInfo[2]);
        String [] days={String.valueOf(selectYear),String.valueOf(selectMonth),String.valueOf(day)};
        DayBean dayInfo = holidayDbDao.getHoliday(days);
        int betweenDays=0;
        betweenDays = DateUtils.daysBetween((mCurrYear + "-" + mCurrMonth + "-" + mCurrDay),
                (selectYear + "-" + selectMonth + "-" + day));

        mDateTv.setText(days[0]+"年"+(selectMonth)+"月"+days[2]+"日");
        mLunarTv.setText("农历"+chinaMonthString+"月"+chinaDayString);
        mWeekTv.setText(selectWeek);

        mAfterTv.setText(betweenDays+"天后");

        String cando = dayInfo.getCando();
        cando= replaceWithBlank(cando);
        mCandoTv.setText(cando);
        mCanNotdoTv.setText(replaceWithBlank(dayInfo.getCannotDo()));

        int flag = dayInfo.getFlag();
        if(flag==CANWEDDING) {
            if(cando.contains("嫁娶")){
                mCandoTv.setText(strWithColor(cando));
            }
            mIsHolidayTv.setVisibility(View.VISIBLE);
            mIsHolidayTv.setBackgroundResource(R.drawable.sp_round4_redmain);
            mIsHolidayTv.setText("宜嫁娶");
        }else if(flag==CANNOTWEDDING){
            mIsHolidayTv.setVisibility(View.VISIBLE);
            mIsHolidayTv.setBackgroundResource(R.drawable.sp_round4_yellow);
            mIsHolidayTv.setText("忌嫁娶");
        }else{
            mIsHolidayTv.setVisibility(View.GONE);
        }
        lastYear=selectYear;
        lastMonth=selectMonth;
        lastDay=day;
    }


    private void showdatePopupWindow(View view) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.pop_tools_holiday_date, null);
        TextView mCancelTv = (TextView) contentView.findViewById(R.id.tv_cancel);
        TextView mConfimTv = (TextView) contentView.findViewById(R.id.tv_confim);
        mViewYear = (WheelView) contentView.findViewById(R.id.id_hour);
        mViewMonth = (WheelView) contentView.findViewById(R.id.id_minute);

        mCancelTv.setOnClickListener(this);
        mConfimTv.setOnClickListener(this);

        // 添加change事件
        mViewYear.addChangingListener(this);
        // 添加change事件
        mViewMonth.addChangingListener(this);

        setUpData();
        mDatePopupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);

        //点击空白处时，隐藏掉pop窗口
        mDatePopupWindow.setTouchable(true);



        mDatePopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        mDatePopupWindow.setBackgroundDrawable(new BitmapDrawable() {});

        mDatePopupWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

    }


    private void setUpData() {
        String [] years=new String[11];
        for (int i = 0; i <11 ; i++) {
            years[i]=2014+i+"年";
        }
        ArrayWheelAdapter yearWheelAdapter = new ArrayWheelAdapter(this,years);
        String [] months=new String[12];
        for (int i = 0; i <12 ; i++) {
            months[i]=1+i+"月";
        }
        ArrayWheelAdapter montnWheelAdapter = new ArrayWheelAdapter<String>(this,months);

        mViewYear.setViewAdapter(yearWheelAdapter);
        mViewMonth.setViewAdapter(montnWheelAdapter);

        // 设置可见条目数量
        mViewYear.setVisibleItems(7);
        mViewMonth.setVisibleItems(7);

        mViewYear.setCurrentItem(2);
        mViewMonth.setCurrentItem(mCurrMonth-1);

        mViewYear.setCyclic(false);
        mViewMonth.setCyclic(false);

    }


    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        if( wheel==mViewYear) {
            mSelectYear=2014+newValue;
        }else if(wheel == mViewMonth){
            mSelectMonth=newValue+1;
        }


    }



    public SpannableStringBuilder strWithColor(String content){
        int startIndex = content.indexOf("嫁娶");
        ssb = new SpannableStringBuilder(content);
        ssb.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorMainRed)),startIndex,startIndex+2, Spanned.SPAN_POINT_MARK);
        return ssb;
    }

    public String replaceWithBlank(String word){
        if(!TextUtils.isEmpty(word)) {
            word = word.replace("、", " ");
        }

        return word;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if(KeyEvent.KEYCODE_BACK == keyCode) {
            if(mDatePopupWindow!=null) {
                mDatePopupWindow.dismiss();
            }
        }
        return super.onKeyUp(keyCode, event);
    }
}
